<template>
  <div class="like-management-container">
    <!-- 搜索和筛选区域 -->
    <div class="filter-container">
      <el-form :inline="true" :model="queryParams" class="demo-form-inline">
        <el-form-item label="用户">
          <el-input v-model="queryParams.username" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item label="目标类型">
          <el-select v-model="queryParams.targettype" placeholder="请选择目标类型" clearable>
            <el-option
              v-for="item in targetTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="目标ID">
          <el-input v-model="queryParams.targetid" placeholder="请输入目标ID" clearable />
        </el-form-item>
        <!-- <el-form-item label="时间范围">
          <el-date-picker
            v-model="queryParams.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item> -->
        <el-form-item>
          <el-button type="primary" @click="handleQuery">搜索</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <div class="table-container">
      <el-table
        ref="tableRef"
        v-loading="loading"
        :data="likeList"
        border
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" align="center" sortable />
        <el-table-column label="用户" width="180" align="center">
          <template #default="{ row }">
            <div class="user-info-cell" @click="handleShowUserInfo(row.userid)">
              <el-avatar :src="row.avatar" />
              <div class="user-info">
                <div class="username">{{ row.username}}</div>
                <div class="user-level">
                  <el-tag v-if="row.user?.verified" size="small" type="success">V</el-tag>
                  <el-tag size="small">Lv.{{ row.user?.level || 0 }}</el-tag>
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="目标类型" width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="targetTypeMap[row.targettype].type">
              {{ targetTypeMap[row.targettype].label }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="目标内容" min-width="300">
          <template #default="{ row }">
            <div v-if="row.targettype === 1" class="target-content">
              <div class="content-type">点赞帖子 {{ row.target_content}}</div>
              <div class="content-title"></div>
              <div class="content-author">
                作者: 
                <el-tag size="small" @click="handleShowUserInfo(row.post?.userid)">
                  {{ row.target_username }}
                </el-tag>
              </div>
            </div>
            <div v-else-if="row.targettype === 2" class="target-content">
              <div class="content-type">点赞评论 {{ row.target_content}} </div>
              <!-- <div class="content-text">评论所属帖子 {{row.main_title}}</div> -->
              <div class="content-author">
                评论人: 
                <!-- <el-tag size="small" @click="handleShowUserInfo(row.comment?.userid)"> -->
                  <el-tag size="small" >
                  {{ row.target_username}}
                </el-tag>
              </div>
              <div v-if="row.main_title" class="content-post">
                所属帖子: {{ row.main_title }}
              </div>
            </div>
            <div v-else-if="row.targettype === 3" class="target-content">
              <div class="content-type">收藏 {{ row.target_content}}</div>
              <div class="content-text"></div>
              <div class="content-author">
                作者: 
                <el-tag size="small" @click="handleShowUserInfo(row.post?.userid)">
                  {{ row.target_username }}
                </el-tag>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="createtime" label="点赞时间" width="180" align="center" sortable>
          <template #default="{ row }">
            {{ formatTime(row.createtime) }}
          </template>
        </el-table-column>
        <el-table-column label="客户端" width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="clientTypeMap[row.clienttype].type">
              {{ clientTypeMap[row.clienttype].label }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right" align="center">
          <template #default="{ row }">
            <el-button size="small" type="danger" @click="handleDelete(row)">
              取消点赞
            </el-button>
            <el-dropdown trigger="click" @command="handleCommand($event, row)">
              <el-button size="small">
                更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="viewTarget">查看目标</el-dropdown-item>
                  <el-dropdown-item command="viewUser">查看用户</el-dropdown-item>
                  <el-dropdown-item command="viewPost" v-if="row.targettype === 2 && row.comment?.postid">
                    查看帖子
                  </el-dropdown-item>
                  <el-dropdown-item command="banUser">封禁用户</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页区域 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 用户信息对话框 -->
    <!-- <el-dialog
      v-model="userInfoVisible"
      title="用户信息"
      width="50%"
      destroy-on-close
    >
      <user-info :user-id="currentUserId" />
    </el-dialog> -->
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowDown } from '@element-plus/icons-vue'
import { formatTime } from '../utils/date'
import request from '../utils/request';
//import UserInfo from '@/components/UserInfo.vue'

// 目标类型映射
const targetTypeMap = {
  1: { label: '帖子', type: 'primary' },
  2: { label: '评论', type: 'success' },
  3: { label: '收藏', type: 'warning' }
}

// 客户端类型映射
const clientTypeMap = {
  1: { label: 'iOS', type: '' },
  2: { label: 'Android', type: 'success' },
  3: { label: 'Web', type: 'primary' }
}

// 目标类型选项
const targetTypeOptions = [
  { value: 1, label: '帖子' },
  { value: 2, label: '评论' },
  { value: 3, label: '收藏' }
]

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  username: '',
  targettype: undefined,
  targetid: '',
  dateRange: []
})

// 表格数据
const likeList = ref([])
const loading = ref(false)
const total = ref(0)

// 对话框控制
const userInfoVisible = ref(false)
const currentUserId = ref(null)

// 获取点赞列表
const getList = async () => {
  try {
    loading.value = true
    const params = {
      ...queryParams,
      startTime: queryParams.dateRange?.[0],
      endTime: queryParams.dateRange?.[1]
    }
    delete params.dateRange
    debugger;
    // 这里替换为实际的API调用
    const res = await request.post('/xhs/like/getLikeList', params);
    likeList.value = res.data.records;
    // likeList.value = res.data.list.map(item => {
    //   // 模拟后端返回的数据结构
    //   return {
    //     ...item,
    //     user: {
    //       username: `用户${item.userid}`,
    //       avatar: `https://randomuser.me/api/portraits/${item.userid % 2 === 0 ? 'women' : 'men'}/${item.userid % 10}.jpg`,
    //       verified: item.userid % 4 === 0,
    //       level: item.userid % 10 + 1
    //     },
    //     post: item.targettype === 1 ? {
    //       title: `帖子标题${item.targetid}`,
    //       author: `作者${item.targetid}`,
    //       userid: item.targetid
    //     } : null,
    //     comment: item.targettype === 2 ? {
    //       content: `这是评论内容${item.targetid}`,
    //       username: `评论用户${item.targetid}`,
    //       userid: item.targetid,
    //       post: {
    //         title: `所属帖子${item.targetid}`,
    //         id: item.targetid
    //       }
    //     } : null,
    //     collect: item.targettype === 3 ? {
    //       title: `收藏内容${item.targetid}`
    //     } : null
    //   }
    // })
    total.value = res.data.total
  } catch (error) {
    console.error('获取点赞列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置搜索
const resetQuery = () => {
  queryParams.pageNum = 1
  queryParams.username = ''
  queryParams.targettype = undefined
  queryParams.targetid = ''
  queryParams.dateRange = []
  getList()
}

// 分页大小改变
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  getList()
}

// 当前页改变
const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  getList()
}

// 删除点赞记录
const handleDelete = (row) => {
  ElMessageBox.confirm(`确认取消这条点赞记录吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 这里替换为实际的API调用
      const res = await request.post('/xhs/like/delete', { id: row.id })
      ElMessage.success('操作成功')
      getList()
    } catch (error) {
      console.error('取消点赞失败:', error)
    }
  }).catch(() => {})
}

// 显示用户信息
const handleShowUserInfo = (userId) => {
  currentUserId.value = userId
  userInfoVisible.value = true
}

// 更多操作
const handleCommand = (command, row) => {
  switch (command) {
    case 'viewTarget':
      handleViewTarget(row)
      break
    case 'viewUser':
      handleShowUserInfo(row.userid)
      break
    case 'viewPost':
      handleViewPost(row.comment?.post?.id)
      break
    case 'banUser':
      handleBanUser(row.userid)
      break
    default:
      break
  }
}

// 查看目标内容
const handleViewTarget = (row) => {
  if (row.targettype === 1) {
    console.log('查看帖子:', row.targetid)
    ElMessage.success(`查看帖子 ${row.targetid}`)
  } else if (row.targettype === 2) {
    console.log('查看评论:', row.targetid)
    ElMessage.success(`查看评论 ${row.targetid}`)
  } else {
    console.log('查看收藏:', row.targetid)
    ElMessage.success(`查看收藏 ${row.targetid}`)
  }
}

// 查看帖子
const handleViewPost = (postId) => {
  console.log('查看帖子:', postId)
  ElMessage.success(`查看帖子 ${postId}`)
}

// 封禁用户
const handleBanUser = (userId) => {
  ElMessageBox.confirm(`确认封禁该用户吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 这里替换为实际的API调用
      const res = await request.post('/xhs/user/ban', { userId })
      ElMessage.success('封禁成功')
      getList()
    } catch (error) {
      console.error('封禁用户失败:', error)
    }
  }).catch(() => {})
}

// 初始化
onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.like-management-container {
  padding: 20px;
  
  .filter-container {
    margin-bottom: 20px;
    padding: 20px;
    background-color: #fff;
    border-radius: 4px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  }
  
  .table-container {
    margin-bottom: 20px;
    padding: 20px;
    background-color: #fff;
    border-radius: 4px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
    
    :deep(.el-table) {
      .user-info-cell {
        display: flex;
        align-items: center;
        cursor: pointer;
        
        .el-avatar {
          margin-right: 10px;
        }
        
        .user-info {
          .username {
            font-weight: 500;
            margin-bottom: 5px;
          }
          
          .user-level {
            display: flex;
            gap: 5px;
            
            .el-tag {
              height: 20px;
              line-height: 20px;
            }
          }
        }
        
        &:hover {
          color: var(--el-color-primary);
        }
      }
      
      .target-content {
        .content-type {
          font-weight: bold;
          margin-bottom: 5px;
        }
        
        .content-title, .content-text {
          margin-bottom: 8px;
          line-height: 1.5;
        }
        
        .content-author, .content-post {
          margin-top: 5px;
          font-size: 12px;
          color: #666;
          
          .el-tag {
            margin-left: 5px;
            cursor: pointer;
          }
        }
      }
    }
  }
  
  .pagination-container {
    display: flex;
    justify-content: flex-end;
    padding: 10px 20px;
    background-color: #fff;
    border-radius: 4px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  }
}
</style>